<template>
    <el-container class="user-container">
      <!-- 搜索功能 -->
      <el-header class="search-header">
        <el-row :gutter="20" justify="space-between" align="middle">
          <el-col :span="8">
            <el-input
              v-model="pagination.search.username"
              placeholder="用户名"
              clearable
              @input="handleSearch"
            >
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-input
              v-model="pagination.search.realName"
              placeholder="真实姓名"
              clearable
              @input="handleSearch"
            >
              <template #prefix><i class="el-icon-search"></i></template>
            </el-input>
          </el-col>
          <el-col :span="8">
            <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
            <el-button plain icon="Refresh" @click="resetSearchForm">重置</el-button>
            <el-button plain icon="Plus" @click="handleAdd">新增用户</el-button>
          </el-col>
        </el-row>
      </el-header>
  
      <!-- 用户表格 -->
      <el-main class="main-content">
        <el-table
          :data="userList"
          stripe
          border
          style="width: 100%"
          v-loading="loading"
          element-loading-text="加载中..."
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="用户ID" width="100" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="name" label="真实姓名" width="180" />
          <el-table-column prop="password" label="密码" width="180" />
          <el-table-column prop="nickname" label="昵称" width="180" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="tel" label="电话" width="180" />
          <el-table-column prop="idCard" label="身份证" width="180" />
          <el-table-column prop="region" label="地区" width="180" />
          <el-table-column prop="points" label="积分" width="100">
            <template #default="{ row }">
              {{ row.points }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="240">
            <template #default="scope">
              <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <div class="pagination-wrapper">
          <el-pagination
            @current-change="handlePageChange"
            :current-page="pagination?.page"
            :page-size="pagination?.size"
            :total="pagination?.total"
            :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
          />
        </div>
      </el-main>
  
      <!-- 弹窗组件 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        :width="dialogWidth"
        class="user-dialog"
      >
        <el-form
          ref="formRef"
          :model="userInfo"
          :rules="formRules"
          label-width="120px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="userInfo.username" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="userInfo.password"
                  type="password"
                  :disabled="isDetail"
                />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="昵称" prop="nickname">
                <el-input v-model="userInfo.nickname" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="name">
                <el-input v-model="userInfo.name" :disabled="isDetail" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="电话" prop="phone">
                <el-input v-model="userInfo.tel" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="userInfo.email" :disabled="isDetail" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证" prop="idCard">
                <el-input v-model="userInfo.idCard" :disabled="isDetail" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地区" prop="region">
                <el-input v-model="userInfo.region" :disabled="isDetail" />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="积分" prop="points">
                <el-input-number v-model="userInfo.points" :disabled="isDetail" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
  
        <template #footer>
          <span v-if="!isDetail">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleSubmit"
              :loading="submitLoading"
            >
              确定
            </el-button>
          </span>
          <span v-else>
            <el-button @click="dialogVisible = false">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </el-container>
  </template>
  
<script>
  import { mapState, mapActions, mapMutations } from 'vuex'

  import { ElMessage, ElMessageBox } from 'element-plus'
  
  export default {
    data() {
      return {
        formValidating: false, // 新增验证状态标识
        loading: false,
        dialogVisible: false,
        submitLoading: false,
        isDetail: false
      }
    },
    computed: {
      ...mapState('commonUser', [
        'userInfo',      // 直接使用 Vuex 中的用户数据
        'userList',
        'currentDialogType',
        'pagination'
      ]),
  
      dialogTitle() {
        return this.currentDialogType === 'add'
          ? '添加用户'
          : this.currentDialogType === 'edit'
          ? '编辑用户'
          : '用户详情'
      },
  
      dialogWidth() {
        return this.currentDialogType === 'detail'
          ? '80%'
          : '600px'
      }
    },
    methods: {
      ...mapActions('commonUser', [
        'fetchUserList',
        'addUser',
        'updateUser',
        'deleteUser'
      ]),
      ...mapMutations('commonUser', [
        'SET_PAGINATION',
        'SET_CURRENT_DIALOG_TYPE',
        'SET_USER_INFO'   // 新增 mutation 用于更新 userInfo
      ]),
  
      // 点击行时更新 userInfo
      handleRowSelect(row) {
        this.SET_USER_INFO(row)
      },
  
      async handleSearch() {
        this.SET_PAGINATION({
          ...this.pagination,
          search: {
            username: this.pagination.search.username,
            realName: this.pagination.search.realName
          }
        })
        this.fetchUserList()
      },
  
      resetSearchForm() {
        this.SET_PAGINATION({
          ...this.pagination,
          search: { username: '', realName: '' }
        })
        this.handleSearch()
      },
  
      handleAdd() {
        this.SET_USER_INFO({})  // 清空 userInfo
        this.SET_CURRENT_DIALOG_TYPE('add')
        this.dialogVisible = true
      },
  
      handleEdit(row) {
        this.SET_USER_INFO(row)  // 直接使用行数据
        this.SET_CURRENT_DIALOG_TYPE('edit')
        this.dialogVisible = true
      },
  
      handleDetail(row) {
        this.SET_USER_INFO(row)
        this.SET_CURRENT_DIALOG_TYPE('detail')
        this.dialogVisible = true
      },
  
      async handleDelete(row) {
        try {
          await ElMessageBox.confirm('确定删除该用户吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          this.SET_USER_INFO(row)
          await this.deleteUser(this.userInfo.id)
          ElMessage.success('删除成功')
          this.dialogVisible = false
          this.fetchUserList()
        } catch (error) {
          console.error('删除失败:', error)
        }
      },
  
      handleSizeChange(size) {
        this.SET_PAGINATION({ ...this.pagination, size })
        this.fetchUserList()
      },
  
      handleCurrentChange(page) {
        this.SET_PAGINATION({ ...this.pagination, page })
        this.fetchUserList()
      },
  
      formatDate(date) {
        if (!date) return ''
        const d = new Date(date)
        return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
      },
  
        async handleSubmit() {
            // 增加表单存活检查
            if (!this.$refs.formRef || this.formValidating) return;
            
            try {
                this.formValidating = true;
                await this.$refs.formRef.validate();
                
                if (this.currentDialogType === 'add') {
                    await this.addUser(this.userInfo)
                    ElMessage.success('添加成功')
                } else {
                    await this.updateUser({id: this.userInfo.id ,data: this.userInfo})
                    ElMessage.success('更新成功')
                }

                this.dialogVisible = false
                await this.fetchUserList()
                
            } catch (error) {
                console.error('验证失败:', error);
            } finally {
                this.formValidating = false;
            }
        },
        beforeUnmount() {
            // 组件卸载时重置状态
            this.formValidating = false;
        },
    },
    watch: {
      dialogVisible(newVal) {
        if (!newVal) {
          this.SET_USER_INFO({})  // 关闭弹窗时清空数据
        }
      }
    },
    created() {
      this.fetchUserList()
    }
  }
  </script>
  <style scoped>
  .user-container {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
  }
  
  .search-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .main-content {
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  }
  
  .pagination-wrapper {
    margin-top: 20px;
    text-align: right;
  }
  
  .user-dialog {
    border-radius: 16px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  }
  
  .dialog-form {
    padding: 24px;
  }
  
  .el-row {
    margin-bottom: 20px;
  }
  
  .el-col:last-child {
    margin-bottom: 0;
  }
  
  @media (max-width: 768px) {
    .el-col {
      width: 100% !important;
    }
  }
  </style>